package com.zby.admin.controller;

import com.zby.admin.pojo.dto.ProductsDto;
import com.zby.admin.pojo.vo.ProductVo;
import com.zby.admin.service.ProductService;
import com.zby.utils.PageResult;
import com.zby.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Resource
    private ProductService productService;

    @GetMapping("/list")
    public Result<PageResult<ProductVo>> list(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "10") Integer pageSize) {
        PageResult<ProductVo> pageResult = productService.selectList(page, pageSize);
        return Result.success(pageResult);
    }

    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody ProductsDto productsDto, HttpServletRequest request) {
        boolean result = productService.addData(productsDto, request);
        if (!result) {
            return Result.error(500, "添加失败");
        }
        return Result.success();
    }

    @PutMapping("/edit")
    public Result<Boolean> edit(@RequestBody ProductsDto productsDto) {
        boolean result = productService.updateData(productsDto);
        if (!result) {
            return Result.error(500, "修改失败");
        }
        return Result.success(true);
    }

    @DeleteMapping("/delete")
    public Result<Boolean> delete(@RequestParam Long id) {
        boolean result = productService.deleteById(id);
        if (!result) {
            return Result.error(500, "删除失败");
        }
        return Result.success(true);
    }

    // 个人商品查询
    @GetMapping("/personalList")
    public Result<PageResult<ProductVo>> personalList(@RequestParam(defaultValue = "1") Integer page,
                                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest request) {
        // 从session中获取用户ID
        Object userIdObj = request.getSession().getAttribute("userId");
        if (userIdObj == null) {
            return Result.error(401, "未登录");
        }

        // 安全地转换为Long类型
        Long userId;
        try {
            userId = Long.valueOf(userIdObj.toString());
        } catch (NumberFormatException e) {
            return Result.error(401, "用户ID格式错误");
        }

        PageResult<ProductVo> pageResult = productService.selectListByUserId(userId, page, pageSize);
        return Result.success(pageResult);
    }
}